<template>
    <div>
        <el-dialog destroy-on-close :before-close="closeDialog" v-model="state.dialog.isShowDialog"
            :title="state.dialog.title">
            <el-cascader-panel size='large' :options="state.options" :props="props" clearable
                 @change="handleChange">
                <template #default="{ node, data }">
                    <div>
                        <span>{{ data.name }}</span>
                        <span>{{ `(${data.code})` }}</span>
                    </div>
                </template>
            </el-cascader-panel>
            <el-button size="small" type="primary" @click="onSubmit">
                关联
            </el-button>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import { usePersonOrgTreeApi } from '/@/api/person/org';
import { ElMessage } from 'element-plus';
import { useAccessRuleAddOrgApi } from '/@/api/access/rule';

// 定义变量内容
const emit = defineEmits(['refresh'])
const state = reactive({
    // 弹窗信息
    dialog: {
        isShowDialog: false,
        type: 0,
        title: '',
        loading: false,
    },
    // 表单提交
    formData: {
        code: '',
        codeIndex: ''
    },
    options: [],
})

const props = {
    value: 'code',
    label: 'name',
    children: 'children',
    checkStrictly: true,
}

const handleChange = (value: any) => {
    state.formData.codeIndex = value[value.length - 1]
    console.log(state.formData.codeIndex)
}


// 打开dialog
const openDialog = (row: { code: string; name: string }) => {
    state.formData.code = row.code
    state.dialog.title = `新增 权限:${row.name} 部门关联(包含子部门)`
    state.dialog.isShowDialog = true
    usePersonOrgTreeApi('').then(({ content }) => {
        state.options = content
    })
}
const onSubmit = () => {
    console.log(state.formData);
    useAccessRuleAddOrgApi(state.formData).then(() => {
        ElMessage.success('关联成功')
        closeDialog()
    })

}
const closeDialog = () => {
    emit('refresh')
    state.dialog.isShowDialog = false
}

// 暴露变量
defineExpose({
    openDialog
})

</script>
